package com.vercon.otamirror.utils.helper;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.backup.BackupManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.session.MediaController;
import android.media.session.MediaSessionManager;
import android.media.session.PlaybackState;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.abupdate.trace.Trace;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.vercon.commonmirror.Constants;
import com.vercon.commonmirror.base.BaseEvent;
import com.vercon.commonmirror.cache.MirrorDataStorage;
import com.vercon.commonmirror.utils.APPUtil;
import com.vercon.commonmirror.utils.LogUtils;
import com.vercon.commonmirror.utils.ThreadUtil;
import com.vercon.commonmirror.utils.langlib.CLang;
import com.vercon.otamirror.MainApplication;
import com.vercon.otamirror.R;

import com.vercon.otamirror.download.RootCmd;

import com.vercon.otamirror.mode.FirmwareContenMode;


import org.greenrobot.eventbus.EventBus;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * Created by csh on 2021/11/26
 */
public class AppUtil {


    /**
     * 获取变化后的sn号
     * @return
     */
    public static String getSerialEncryptionNum() {
        //获取加密的手机序列号
        String serial = getSerialNumber();
        LogUtils.i("APPUtil", "变化前：" + serial);
        if (serial.length() > 12) {
            serial = serial.substring(0, 12);
        } else if (serial.length() < 12) {
            return serial;
        }
        LogUtils.i("APPUtil", "变化前截断：" + serial);
        String[] num = new String[12];
        for (int i = 0; i < serial.length(); i++) {
            num[i] = serial.substring(i, i + 1);
        }
        serial = num[0] + num[11] + num[1] + num[10] + num[2] + num[9] + num[3] + num[8] + num[4] + num[7] + num[5] + num[6];

        LogUtils.i("getSerialEncryptionNum", "变化后：" + serial);

        return serial;
    }
    /**
     * 获取手机序列号
     *
     * @return 手机序列号
     */
    public static String getSerialNumber() {
        String serial = "";
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {//9.0+
                serial = Build.getSerial();
            } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {//8.0+
                serial = Build.SERIAL;
            } else {//8.0-
                Class<?> c = Class.forName("android.os.SystemProperties");
                Method get = c.getMethod("get", String.class);
                serial = (String) get.invoke(c, "ro.serialno");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("APPUtil", e.getMessage());

        }
        return serial;
    }

    /**
     * 获取SN号
     *
     * @return SN 号
     */
    public static String getSN() {
        String sn;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (ActivityCompat.checkSelfPermission(MainApplication.sCx, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                Trace.d("TAG", "getIMEI() fail, Because of lack of permissions: " + Manifest.permission.READ_PHONE_STATE);
                return "";
            }
            sn = Build.getSerial();
        } else {
            sn = Build.SERIAL;
        }
        if (isValidMid(sn)) {
            return sn;
        }
        Trace.d("iport", "get SN failed");
        return "";
    }
    /**
     * mid是否合法
     *
     * @param mid
     * @return
     */
    public static boolean isValidMid(String mid) {
        Trace.d("TAG", "isValidMid() " + mid);
        return !TextUtils.isEmpty(mid) &&
                !"unknown".equalsIgnoreCase(mid) &&
                !"null".equalsIgnoreCase(mid) &&
                mid.length() >= 4 &&
                mid.length() <= 64 &&
                !mid.startsWith(DEFAULT_SN);
    }
    public static final String DEFAULT_SN = "default-sn";


    public static String getContent (String message){
        String content = "";

        Gson gson = new Gson();
        Type type = new TypeToken<List<FirmwareContenMode>>(){}.getType();
        List<FirmwareContenMode> list = gson.fromJson(message,type);
        if (list != null && list.size() > 0) {
            FirmwareContenMode mode = list.get(0);
            content = mode.content;
        }
        //LogUtils.e("mode.content="+mode.content);
        return content;
    }

    public  static final boolean ping() {

        String result = null;
        try {
            String ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网
            Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
            // 读取ping的内容，可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }

//            Log.d("------ping-----", "result content : " + stringBuffer.toString());
            // ping的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
//            Log.d("----result---", "result = " + result);
        }
        return false;
    }

    private static long lastClickTime = 0;
    private static final int CLICK_TIME = 2000; //快速点击间隔时间

    // 判断按钮是否快速点击
    public static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < CLICK_TIME) {//判断系统时间差是否小于点击间隔时间
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public static void writeDataStart(String log, Context context){
        String SDPATH;
        File fileDir;
        SDPATH = Environment.getExternalStorageDirectory().toString() + "/" + context.getPackageName() + "_logFiles";
        fileDir = new File(SDPATH);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        File file = new File(SDPATH + "/",  "creat.txt");
        FileOutputStream outputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            outputStream = new FileOutputStream(file,true);
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            bufferedOutputStream.write(log.getBytes());
            bufferedOutputStream.flush();
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }

    public static PackageInfo getPackageInfo(Context context, String packageName){
        PackageManager mPm = context.getPackageManager();
        List<PackageInfo> packageInfo = mPm.getInstalledPackages(0);

        for (PackageInfo info : packageInfo) {
            if (info.packageName.equalsIgnoreCase(packageName))
                return info;
        }
        return null;
    }

    public static String getCountry(String language) {
        try {
            if (language.equals("zh_tw")) {
                return "TW";
            }
            for (String s : mStrings) {
                String[] s1 = s.split("_");
                if (s1.length >= 2) {
                    if (s1[0].equals(language)) {
                        return s1[1];
                    }
                }
            }
        }catch (Exception e){}


        return "";
    }

    private static final String[] mStrings = new String[]{
            "zh_CN", "en_AU", "en_IN", "fr_FR", "it_IT", "es_ES", "et_EE", "de_DE", "nl_NL", "cs_CZ", "pl_PL", "ja_JP",
            "zh_TW", "en_US", "zh_HK", "ru_RU", "ko_KR", "nb_NO", "es_US", "da_DK", "el_GR", "tr_TR", "pt_PT", "pt_BR", "rm_CH", "sv_SE", "bg_BG",
            "ca_ES", "en_GB", "fi_FI", "hi_IN", "hr_HR", "hu_HU", "in_ID", "iw_IL", "lt_LT", "lv_LV", "ro_RO", "sk_SK", "sl_SI", "sr_RS", "uk_UA",
            "vi_VN", "tl_PH", "ar_EG", "fa_IR", "th_TH", "sw_TZ", "ms_MY", "af_ZA", "zu_ZA", "am_ET", "hi_IN", "en_XA", "fr_CA", "km_KH",
            "lo_LA", "ne_NP", "si_LK", "mn_MN", "hy_AM", "az_AZ", "ka_GE", "my_MM", "mr_IN", "ml_IN", "is_IS", "mk_MK", "ky_KG", "eu_ES", "gl_ES",
            "bn_BD", "ta_IN", "kn_IN", "te_IN", "uz_UZ", "ur_PK", "kk_KZ"
    };

    /**
     * 各语言关键字
     * 调用
     * changeSystemLanguage("zh", "CN");//中文
     * zh_CN en_AU en_IN fr_FR it_IT es_ES et_EE de_DE nl_NL cs_CZ pl_PL ja_JP
     * zh_TW en_US zh_HK ru_RU ko_KR nb_NO es_US da_DK el_GR tr_TR pt_PT pt_BR rm_CH sv_SE bg_BG
     * ca_ES en_GB fi_FI hi_IN hr_HR hu_HU in_ID iw_IL lt_LT lv_LV ro_RO sk_SK sl_SI sr_RS uk_UA
     * vi_VN tl_PH ar_EG fa_IR th_TH sw_TZ ms_MY af_ZA zu_ZA am_ET hi_IN en_XA ar_XB fr_CA km_KH
     * lo_LA ne_NP si_LK mn_MN hy_AM az_AZ ka_GE my_MM mr_IN ml_IN is_IS mk_MK ky_KG eu_ES gl_ES
     * bn_BD ta_IN kn_IN te_IN uz_UZ ur_PK kk_KZ
     *
     * @param language
     * @param country
     */
    public static void changeSystemLanguage(String language, String country) {
        //Locale mLocale = new Locale("en", "ZA");
        Locale mLocale = new Locale(language, country);
        LogUtils.d("LanguageFragment  " + language + "  " + country);
        try {
            Class iActivityManager = Class.forName("android.app.IActivityManager");
            Class activityManagerNative = Class.forName("android.app.ActivityManagerNative");
            Method getDefault = activityManagerNative.getDeclaredMethod("getDefault");
            Object objIActMag = getDefault.invoke(activityManagerNative);
            Method getConfiguration = iActivityManager.getDeclaredMethod("getConfiguration");
            Configuration config = (Configuration) getConfiguration.invoke(objIActMag);
            config.locale = mLocale;
            Class clzConfig = Class.forName("android.content.res.Configuration");
            java.lang.reflect.Field userSetLocale = clzConfig.getField("userSetLocale");
            userSetLocale.set(config, true);
            Class[] clzParams = {Configuration.class};
            Method updateConfiguration = iActivityManager.getDeclaredMethod("updateConfiguration", clzParams);
            updateConfiguration.invoke(objIActMag, config);
            BackupManager.dataChanged("com.android.providers.settings");
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.d("LanguageFragment  " + language + "  " + country + "  " + e.getMessage());

        }

    }

    public static void wakeLock(Context context) {
        try {
            if (context != null) {
                LogUtils.d("亮屏");
                Intent intent = new Intent();
                intent.setAction("android.56iq.intent.action.OPEN_SCREEN");
                context.sendBroadcast(intent);
                EventBus.getDefault().post(new BaseEvent(Constants.screen_event));
                EventBus.getDefault().post(new BaseEvent(Constants.sleep_event));
                EventBus.getDefault().post(new BaseEvent(Constants.brightScreen));
            }
        }catch (Exception e){

        }

    }

    public static void wakeLockOff(Context context) {
        try {
            if (context != null) {
                LogUtils.d("息屏");
                Intent intent = new Intent();
                intent.setAction("android.56iq.intent.action.CLOSE_SCREEN");
                context.sendBroadcast(intent);
            }
        }catch (Exception e){

        }
    }
    private static String radarResult;//S系列雷达数据
    private static int num = 0;
    public static void sreen_On_3288(Context context) {
        radarResult = RootCmd.execRadar(Constants.commend1_7_1);
        if (!TextUtils.isEmpty(radarResult)) {
//            LogUtils.d("radarResult=", radarResult);
            num = Integer.parseInt(radarResult);
            if (num > 20 ) {
                wakeLock(context);
            }
        }
    }

    public static void addPackageName(String packageName) {
        Constants.listApkName.add(packageName);
        Set set = new HashSet(Constants.listApkName);
        List tempList = new ArrayList(set);
        Constants.listApkName = tempList;
    }

    /**
     * 杀死除了 自身应用和将要打开的应用 以外的其他应用
     * @param mContext
     * @param openAppPackageName
     */
    public static void killOtherApp(Context mContext,String openAppPackageName){

        final String[] otheruncheckApp = {"deezer.android.app.nobilling"};

        ThreadUtil.getInstance().getExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                ComponentName componentName = new ComponentName(MainApplication.getContext(), MainApplication.getContext().getClass());
                MediaSessionManager mSessionManager =  (MediaSessionManager) MainApplication.getContext().getSystemService(Context.MEDIA_SESSION_SERVICE);
                AudioManager mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);

                PackageManager localPackageManager = mContext.getPackageManager();
                List localList = localPackageManager.getInstalledPackages(0);
                for (int i = 0; i < localList.size(); i++) {
                    PackageInfo localPackageInfo1 = (PackageInfo) localList.get(i);
                    String packageName = localPackageInfo1.packageName.split(":")[0];
                    if (((ApplicationInfo.FLAG_SYSTEM & localPackageInfo1.applicationInfo.flags) == 0)
                            && ((ApplicationInfo.FLAG_UPDATED_SYSTEM_APP & localPackageInfo1.applicationInfo.flags) == 0)
                            && ((ApplicationInfo.FLAG_STOPPED & localPackageInfo1.applicationInfo.flags) == 0)) {
                        System.out.println("packageName =====> 进程应用: " + packageName);
                        if(packageName.equals(mContext.getPackageName())) {
                            continue;
                        }

                        if(packageName.equals(openAppPackageName)){
                            continue;
                        }

                        if("deezer.android.app.nobilling".equals(packageName)){
                            continue ;
                        }
                        if("com.doorbird.doorbird".equals(packageName)){
                            continue ;
                        }
                        //过滤正在播放音乐的应用
                        String musicActivePackgeName = "";
                        List<MediaController> controllers = mSessionManager.getActiveSessions(componentName);
                        for (MediaController mediaController : controllers){
                            if(mediaController.getPlaybackState() != null){
                                if(mediaController.getPlaybackState().getState() == PlaybackState.STATE_PLAYING){
                                    System.out.println("packageName =====> 正在播放音乐的应用: " +  mediaController.getPackageName());
                                    musicActivePackgeName = mediaController.getPackageName();
                                }
                            }
                        }
                        if(packageName.equals(musicActivePackgeName) && mAudioManager.isMusicActive()){
                            continue;
                        }

                        ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
                        Method forceStopPackage = null;
                        try {
                            forceStopPackage = activityManager.getClass().getDeclaredMethod("forceStopPackage", String.class);
                            forceStopPackage.setAccessible(true);
                            forceStopPackage.invoke(activityManager, packageName);
                            System.out.println("packageName =====> 杀死的应用: " + packageName);
                        } catch (NoSuchMethodException e) {
                            LogUtils.e("forceStopPackage NoSuchMethodException error = " + e.getMessage());
                        } catch (IllegalAccessException e) {
                            LogUtils.e("forceStopPackage IllegalAccessException error = " + e.getMessage());
                        } catch (InvocationTargetException e) {
                            LogUtils.e("forceStopPackage InvocationTargetException error = " + e.getMessage());
                        }
                    }
                }
            }
        });
    }
    /**
     * 当前的包名的app，是不是视频类型app
     */
    public static boolean isvideoapp(String packname){
        boolean aa = false;
        String[] videoapp = {"com.kwai.tv.yst","com.ktcp.svideo","com.netflix.mediaclient","com.imgur.mobile",
                "tv.mirada.iris.android.inspire.skygo","video.like","com.zhiliaoapp.musically","hdpfans.com","bbc.iplayer.android",
                "cn.cibntv.ott","com.google.android.youtube","com.qiyi.video.pad"};
        for (int i = 0;i < videoapp.length;i++){
            if (packname.equals(videoapp[i])){
                aa = true;
                break;
            }
        }
        return aa;
    }

    //获取指定语言的资源
     public static Resources getLocalizedResources(Context context, Locale desiredLocale) {
        Configuration conf = context.getResources().getConfiguration();
        conf = new Configuration(conf);
        conf.setLocale(desiredLocale);
        Context localizedContext = context.createConfigurationContext(conf);
        return localizedContext.getResources();
    }
    /**
     * 获取当天时间点
     * @return
     */
    public static String getNowtime(){
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date today = new Date(System.currentTimeMillis());
        String todayString = format.format(today);
        LogUtils.e("todayString="+todayString);
        return todayString;
    }

    public static final String EXTRA_REASON = "android.intent.extra.REASON";
    public static final String EXTRA_WIPE_EXTERNAL_STORAGE = "android.intent.extra.WIPE_EXTERNAL_STORAGE";

    public static final String EXTRA_WIPE_ESIMS = "com.android.internal.intent.extra.WIPE_ESIMS";

    public static final String ACTION_FACTORY_RESET = "android.intent.action.FACTORY_RESET";

    /**
     * 系统方式，直接恢复系统设置
     * @param context
     */
    public static  void doMasterClear(Context context) {
        boolean mEraseSdCard = false;
        boolean mEraseEsims = true;
        Intent intent = new Intent(ACTION_FACTORY_RESET);
        intent.setPackage("android");
        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        intent.putExtra(EXTRA_REASON, "MasterClearConfirm");
        intent.putExtra(EXTRA_WIPE_EXTERNAL_STORAGE, mEraseSdCard);
        intent.putExtra(EXTRA_WIPE_ESIMS, mEraseEsims);
        context.sendBroadcast(intent);
        // Intent handling is asynchronous -- assume it will happen soon.
    }




    /**
     * 判断某个界面是否在前台
     *
     * @param context Activity的getAppliction()获取
     * @param className Activity名称 由类名.class.getName()获取
     *
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className)) {
            return false;
        }
        ActivityManager am =(ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            return className.equals(cpn.getClassName());
        }
        return false;
    }




    /**
     * 获取当前日期是星期几
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate() {
        Date date = new Date(System.currentTimeMillis());
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        //String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }
    public  static String formatMonthTime(long ms, TextView textView) {

        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;

        long day = ms / dd;
        long hour = (ms - day * dd) / hh;
        long minute = (ms - day * dd - hour * hh) / mi;
        long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

        String strDay = day < 10 ? "" + day : "" + day; //天
        String strHour = hour < 10 ? "" + hour : "" + hour;//小时
        String strMinute = minute < 10 ? "" + minute : "" + minute;//分钟
        String strSecond = second < 10 ? "" + second : "" + second;//秒
        String strMilliSecond = milliSecond < 10 ? "" + milliSecond : "" + milliSecond;//毫秒
        strMilliSecond = milliSecond < 100 ? "" + strMilliSecond : "" + strMilliSecond;
        LogUtils.e("strDay="+strDay+" strHour="+strHour+" strMinute="+strMinute+" second="+second);
        // if ()

        if (Integer.parseInt(strHour) > 0){
            textView.setText("小时");
            return strHour;
        }else if (Integer.parseInt(strMinute) > 0){
            textView.setText("分钟");
            return strMinute;
        } else if (Integer.parseInt(strMinute) > 0){
            textView.setText("秒");
            return strSecond;
        }
        return strMinute;
    }

}